#include <48func.h>
int main(int argc, char *argv[])
{
    // ./2_azhen 192.168.118.128 1234
    ARGS_CHECK(argc,3);
    int sockfd = socket(AF_INET,SOCK_STREAM,0);//ipv4 tcp
    struct sockaddr_in serverAddr;
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = htons(atoi(argv[2]));
    serverAddr.sin_addr.s_addr = inet_addr(argv[1]);
    int reuseArg = 1;
    int ret = setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&reuseArg,sizeof(reuseArg));
    ERROR_CHECK(ret,-1,"setsockopt");
    ret = bind(sockfd,(struct sockaddr *)&serverAddr,sizeof(serverAddr));
    ERROR_CHECK(ret,-1,"bind");
    ret = listen(sockfd,10);
    ERROR_CHECK(ret,-1,"listen");
    struct sockaddr_in clientAddr;
    socklen_t socklen = sizeof(clientAddr);//socklen必须初始化
    int netfd = accept(sockfd,(struct sockaddr *)&clientAddr,&socklen);
    ERROR_CHECK(netfd,-1,"accept");
    printf("client ip = %s, port = %d\n",
            inet_ntoa(clientAddr.sin_addr),
            ntohs(clientAddr.sin_port));
    char buf[4096] = {0};
    fd_set rdset;
    while(1){
        FD_ZERO(&rdset);
        FD_SET(STDIN_FILENO,&rdset);
        FD_SET(netfd,&rdset);
        select(netfd+1,&rdset,NULL,NULL,NULL);
        if(FD_ISSET(STDIN_FILENO,&rdset)){
            bzero(buf,sizeof(buf));
            ssize_t sret = read(STDIN_FILENO,buf,sizeof(buf));
            if(sret == 0){ // ctrl+d
                send(netfd,"nishigehaoren",13,0);
                break;
            }
            send(netfd,buf,strlen(buf),0);
        }
        if(FD_ISSET(netfd,&rdset)){
            bzero(buf,sizeof(buf));
            ssize_t sret = recv(netfd,buf,sizeof(buf),0);
            if(sret == 0){ // 对面close了
                printf("I quit!\n");
                break;
            }
            printf("buf = %s\n", buf);
        }
    }
    close(netfd);
    close(sockfd);
    return 0;
}






